package com.authsphere.springboot.starter.security;

import com.authsphere.plugin.api.AuthSphereAfterPlugin;
import com.authsphere.plugin.api.AuthSphereBeforePlugin;
import com.authsphere.plugin.api.AuthSpherePlugin;
import com.authsphere.plugin.base.scanner.AnnotationScanner;
import com.authsphere.security.web.handler.AuthSphereAuthenticationHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/26 09:51
 **/
@Configuration
public class AuthSphereSecurityConfiguration {

    @Bean
    public AnnotationScanner annotationScanner() {
        return new AnnotationScanner();
    }

    /**
     * init AuthSphereAuthenticationHandler
     * @param beforePlugins this plugins is All impl AuthSphereBeforePlugin.
     * @param afterPlugins this plugins is All impl AuthSphereAfterPlugin.
     * @return {@linkplain AuthSphereAuthenticationHandler}
     */
    @Bean("authenticationHandler")
    public AuthSphereAuthenticationHandler authSphereAuthenticationHandler(final ObjectProvider<List<AuthSphereBeforePlugin>> beforePlugins,
                                                                           final ObjectProvider<List<AuthSphereAfterPlugin>> afterPlugins) {
        List<AuthSphereBeforePlugin> beforePluginList = beforePlugins.getIfAvailable(Collections::emptyList);
        List<AuthSphereAfterPlugin> afterPluginList = afterPlugins.getIfAvailable(Collections::emptyList);
        List<AuthSphereBeforePlugin> sortedBeforePlugins = beforePluginList.stream()
                .sorted(Comparator.comparingInt(AuthSpherePlugin::getOrder)).toList();
        List<AuthSphereAfterPlugin> sortedAfterPlugins = afterPluginList.stream()
                .sorted(Comparator.comparingInt(AuthSpherePlugin::getOrder)).toList();
        return new AuthSphereAuthenticationHandler(sortedBeforePlugins, sortedAfterPlugins);
    }

}
